<template>
	<a-popover trigger="click" :arrow-style="{
		width: '0px',
		height: '0px'
	}" @popup-visible-change="()=>{total = 0;}">
		<a-badge :max-count="99" :count="cartList.total">
			<a-button type="primary">
				<template #icon>
					<i class="iconfont iconfont-mart"></i>
				</template>
				<template #default>
					购物车
				</template>
			</a-button>
		</a-badge>
		<template #content>
			<a-table :data="cartList.data" :filter-icon-align-left="true" :row-selection="{
					type:'checkbox',
					showCheckedAll:true
			}" :pagination="{
				pageSize: 5
			}" style="width: 800px;" @select="chooseGoods" @select-all="chooseAll" @selection-change="chooseChange"
				ref="shoppingCart" @cell-click="test">
				<template #columns>
					<a-table-column v-for="(item,index) in columns" :title="item.title" :sortable="item.sortable"
						:filterable="item.filterable" ellipsis>
						<template #cell="{record}">
							<a-tooltip :content="record[item.dataIndex].toString()"
								v-if="item.dataIndex == 'name' || item.dataIndex == 'info'" position="bottom"
								:arrow-style="{
									width: '0px',
									height: '0px'
								}">
								<span v-if="item.dataIndex == 'name' || item.dataIndex == 'info'">
									{{record[item.dataIndex]}}
								</span>
							</a-tooltip>
							<span v-if="item.dataIndex == 'sPrice'">
								{{record[item.dataIndex]}}
							</span>
						</template>
					</a-table-column>
					<a-table-column title="数量">
						<template #cell="{record}">
							<a-input-number :default-value="1" :model-value="record.amount" mode="button" size="small"
								@change="changeAmount" @blur="blurAmount(record)" @focus="focusAmount(record)"
								:min="1" :max="5" />
						</template>
					</a-table-column>
					<a-table-column title="金额">
						<template #cell="{record}">
							{{record.sPrice * record.amount}}
						</template>
					</a-table-column>
					<a-table-column title="操作">
						<template #cell="{record}">
							<a-button type="primary" @click="deleteRowData(record.key)">
								<template #icon>
									<icon-eraser />
								</template>
								<template #default>
									删除
								</template>
							</a-button>
						</template>
					</a-table-column>
				</template>
				<template #footer>
					<a-row align="center" style="margin-right: 1%;">
						<a-col :span="12">
							总计:{{total}}
						</a-col>
						<a-col :span="12" style="text-align: right;">
							<a-space>
								<a-button type="primary" v-if="total > 0" @click="toOrderDetail">
									<template #icon>
										<icon-desktop />
									</template>
									<template #default>
										结算
									</template>
								</a-button>
								<!--未选任何商品时,禁用结算按钮-->
								<a-button type="primary" disabled v-else-if="total == 0">
									<template #icon>
										<icon-desktop />
									</template>
									<template #default>
										结算
									</template>
								</a-button>
							</a-space>
						</a-col>
					</a-row>
				</template>
			</a-table>
		</template>
	</a-popover>
</template>

<script setup>
	import {
		ref,
		reactive,
		getCurrentInstance,
		onMounted,
		inject,
		nextTick,
		watch
	} from 'vue';

	//国际化组件
	import enUS from '@arco-design/web-vue/es/locale/lang/en-us';
	import zhCN from '@arco-design/web-vue/es/locale/lang/zh-cn';

	import apiUrl from '@/constant/index/apiUrl.js';
	import indexApi from '@/module/shoppingCart/api/index.js';
	import jwt_decode from 'jwt-decode';

	import {
		useRouter
	} from 'vue-router';
	import {
		useRoute
	} from 'vue-router';
	let router = useRouter();
	let route = useRoute();

	const props = defineProps({
		formVisible: Boolean,
		loginForm: Object
	});

	const emit = defineEmits(['loginVisibleShow', 'registerVisibleShow']);

	let {
		proxy
	} = getCurrentInstance();

	let language = ref(zhCN);

	let columns = reactive([{
			title: '商品名称',
			dataIndex: 'name',
			sortable: {
				sortDirections: ['ascend', 'descend']
			}
		},
		{
			title: '商品信息',
			dataIndex: 'info'
		},
		{
			title: '单价',
			dataIndex: 'sPrice',
			filterable: {
				filters: [{
						text: '> 1000',
						value: '1000',
					},
					{
						text: '> 5000',
						value: '5000',
					}
				],
				filter: (value, record) => record.sPrice > value
			}
		}
	]);
	let cartList = reactive({});
	let shoppingCart = ref(null);
	let total = ref(0);
	let currentRowData = reactive({});
	let currentRowAmount = ref(0);
	let currentRowOperate = ref(0);
	let rowKeysAllChecked = reactive([]);
	let rowKeysPlus = reactive([]);
	let rowKeysDiffer = reactive([]);
	let PlusSum = ref(0);
	let DifferSum = ref(0);
	
	let detailInfo = reactive([]);
	let saveGoodsStatus = reactive([]);
	let deleteGoodsStatus = reactive({});

	function changeAmount(value) {
		console.log('改变后的商品数量为:', value);
		console.log('tableData', shoppingCart.value.data);
		currentRowAmount.value = value;
		console.log('currentRowAmount', currentRowAmount.value);
	}
	
	function blurAmount(data){
		console.log('blur1',currentRowAmount.value);
		console.log('blur2',data);
		console.log('amount',currentRowAmount.value);
		shoppingCart.value.data.map((item, index) => {
			if (item.key == data.key ) {
				item.amount = currentRowAmount.value;
		
				console.log('item.amount', item.amount);
				if (item.amount > data.amount && (rowKeysPlus.indexOf(item.key) != -1)) {
					total.value = total.value + (item.sPrice * (item.amount - data.amount));
				} else if (item.amount < data.amount && (rowKeysPlus.indexOf(item.key) != -1)) {
					total.value = total.value - (item.sPrice * (data.amount - item.amount));
				}
			}
		});
	}
	
	function focusAmount(data){
		currentRowAmount.value = data.amount;
		console.log('focus1',currentRowAmount.value);
		console.log('focus2',data);
	}

	function test(row, col) {
		if (col.title == '数量' && currentRowAmount.value != 0) {
			currentRowData = row;
			console.log('rowData', row);
			shoppingCart.value.data.map((item, index) => {
				if (item.key == currentRowData.key ) {
					item.amount = currentRowAmount.value;

					console.log('item.amount', item.amount);
					if (item.amount > row.amount && (rowKeysPlus.indexOf(item.key) != -1)) {
						total.value = total.value + (item.sPrice * (item.amount - row.amount));
					} else if (item.amount < row.amount && (rowKeysPlus.indexOf(item.key) != -1)) {
						total.value = total.value - (item.sPrice * (row.amount - item.amount));
					}
				}
			});
		}
	}

	function deleteRowData(currentKey) {
		shoppingCart.value.data.map(async(item, index) => {
			if (item.key == currentKey) {
				//删除数据表中的商品
				deleteGoodsStatus.resp = await indexApi.deleteGood(jwt_decode(sessionStorage.getItem("token")).uid,currentKey);
				console.log('deleteGoodsStatus',deleteGoodsStatus.resp);
				if(deleteGoodsStatus.resp.flag == true){
					//更新购物车组件
					nextTick(()=>{
						proxy.$notification.success({content:'删除商品成功',position:'topLeft'});
						//从购物车列表中删除商品
						cartList.data.splice(cartList.data.indexOf(item), 1);
						loadingCart();
					});
				}

				rowKeysPlus.map((plusItem, pIndex) => {
					if (plusItem == item.key && (rowKeysPlus.indexOf(item.key) != -1)) {
						console.log('item+:', item);
						rowKeysPlus.splice(rowKeysPlus.indexOf(item.key),1);
						PlusSum.value = PlusSum.value + (item.sPrice * item.amount);
					}
				});

				rowKeysDiffer.map((diffItem, dIndex) => {
					if (diffItem == item.key && (rowKeysDiffer.indexOf(item.key) != -1)) {
						console.log('item-:', item);
						rowKeysDiffer.splice(rowKeysDiffer.indexOf(item.key),1);
						DifferSum.value = DifferSum.value + (item.sPrice * item.amount);
					}
				});

				console.log('PlusSum', PlusSum.value);
				console.log('DifferSum', DifferSum.value);
				console.log('total', total.value);

				total.value = total.value - PlusSum.value;
				PlusSum.value = 0;
				DifferSum.value = 0;

				console.log('rowKeysPlus', rowKeysPlus);
				console.log('rowKeysDiffer', rowKeysDiffer);
			}
		});
	}

	function chooseGoods(rowKeys) {
		console.log('keys', rowKeys);
		if (rowKeys.length == 0) {
			total.value = 0;
		}
	}

	function chooseChange(rowKeys) {
		loadingrowKeysAllChecked();
		rowKeysDiffer = rowKeysAllChecked.filter((currentItem, index) => {
			return rowKeys.indexOf(currentItem) == -1;
		});

		rowKeysPlus = rowKeysAllChecked.filter((currentItem, index) => {
			return rowKeys.indexOf(currentItem) != -1;
		});

		shoppingCart.value.data.map((item, index) => {
			if (rowKeysPlus.length == 1) {
				rowKeysPlus.map((currentItem, cIndex) => {
					if (currentItem == item.key) {
						total.value = item.sPrice * item.amount;
					}
				});
			} else if (rowKeysPlus.length > 0 && rowKeysDiffer.length > 0 && rowKeysPlus.length < cartList.data
				.length) {
				chooseAll(true);
				rowKeysPlus.map((plusItem, pIndex) => {
					if (plusItem == item.key && (rowKeysPlus.indexOf(item.key) != -1)) {
						console.log('item+:', item);
						PlusSum.value = PlusSum.value + (item.sPrice * item.amount);
					}
				});
				
				rowKeysDiffer.map((diffItem, dIndex) => {
					if (diffItem == item.key && (rowKeysDiffer.indexOf(item.key) != -1)) {
						console.log('item-:', item);
						DifferSum.value = DifferSum.value + (item.sPrice * item.amount);
					}
				});

				console.log('PlusSum', PlusSum.value);
				console.log('DifferSum', DifferSum.value);

				if (total.value - PlusSum.value == DifferSum.value) {
					console.log(1)
					total.value = PlusSum.value;
					PlusSum.value = 0;
					DifferSum.value = 0;
				}

			} else if (rowKeysPlus.length == cartList.data.length) {
				chooseAll(true);
			}else if (rowKeysPlus.length == 0) {
				total.value = 0;
			}
		});

		console.log('rowKeysPlus', rowKeysPlus);
		console.log('rowKeysDiffer', rowKeysDiffer);
	}

	function loadingrowKeysAllChecked() {
		rowKeysAllChecked.splice(0, rowKeysAllChecked.length);
		cartList.data.map((item, index) => {
			rowKeysAllChecked.push(item.key);
		});
	}

	function chooseAll(checked) {
		if (checked == true) {
			total.value = 0;
			shoppingCart.value.data.map((item, index) => {
				total.value = total.value + (item.sPrice * item.amount);
			});
			loadingrowKeysAllChecked();
		} else {
			total.value = 0;
		}
	}
	
	function toOrderDetail(){
		rowKeysPlus.map((currentItem,cIndex)=>{
			shoppingCart.value.data.map((item,index)=>{
				if(currentItem == item.key && (rowKeysPlus.indexOf(item.key) != -1)){
					return detailInfo.push(item);
				}
			});
		});
		console.log('detailInfo',detailInfo);
		saveGoods(detailInfo);
	}
	async function saveGoods(detailInfo){
		saveGoodsStatus.resp = await indexApi.saveGoodsList(jwt_decode(sessionStorage.getItem("token")).uid,detailInfo);
		saveGoodsStatus.flag = saveGoodsStatus.resp.flag;
		console.log('saveGoodsStatus',saveGoodsStatus.resp)
		if(saveGoodsStatus.flag == true){
			saveGoodsStatus.data = saveGoodsStatus.resp.data;
			router.push({name: 'orderDetail',params:{id: saveGoodsStatus.data}});
		}
		else if(saveGoodsStatus.flag == false){
			proxy.$message.error("错误");
		}
	}
	
	if(inject('flushShoppingCart')){
		console.log('flush',inject('flushShoppingCart'));
		let flushStatus = inject('flushShoppingCart');
		watch(()=> flushStatus.value,(newValue,preValue)=>{
			console.log('newValue',newValue);
			console.log('preValue',preValue);
			if(newValue == true){
				nextTick(()=>{
					loadingCart();
				})
			}
		});
	}
	
	async function loadingCart() {
		cartList.total = 0;
		console.log('uid',jwt_decode(sessionStorage.getItem("token")).uid);
		cartList.resp = await indexApi.getCartList(jwt_decode(sessionStorage.getItem("token")).uid);
		cartList.data = cartList.resp.data;
		cartList.total = cartList.resp.total;
		loadingrowKeysAllChecked();
		console.log('cartList', cartList.resp);
		return cartList;
	}
	
	onMounted(() => {
		loadingCart();
	});
</script>

<style lang="less" scoped>
</style>
